## 

rm(list = ls())

library(tidyverse)
library(pbapply)
library(rdrobust)
library(fixest)
library(broom)

## Def covars

covs <- c('turnout_party_2009_btw', 'soz_vers_beschaeftigte_share',
          'pop_density_km2', 'migration_out_share')

## Get municipal data ##

mu <- readRDS('data/data_municipal.rds') %>%
  filter(!is.na(treated)) %>%
  mutate(state_id = substr(ags, 1, 2)) %>% 
  filter(time_rel_period > -2)

## Elections years by state 

time_df <- unique(mu$state_id) %>% 
  lapply(function(s) 
    mu %>% filter(state_id == !!s) %>% 
      pull(year) %>% unique() %>% sort() %>% 
      .[2] %>% ifelse(is.null(.), NA, .)
    ) %>% unlist() %>% 
  data.frame(state_id = unique(mu$state_id),
             last_elec = .) %>% 
  mutate(elec_late = 1*(last_elec>2014)) 
  
## Outcomes

outcomes <- c('agg_left')

## Source helper function to tidy rdrobust output

source("code/tidy_rd.R")

## Get first differences

olist <- c("agg_left")

diff_df <- pblapply(olist, function(o) {
  out <- mu %>%
    filter(time_rel_period > -2) %>%
    mutate(time_rel_period = time_rel_period + 2)  %>% 
    pivot_wider(values_from = o, names_from = 'time_rel_period', 
                id_cols = 'ags',
                names_prefix = 'o') %>%
    mutate(diff = o2  - o1) %>%  dplyr::select(ags, diff) 
  ## Rename
  colnames(out)[2] <- o
  
  ## Return this
  out
}) %>%
  reduce(left_join) %>%
  left_join(mu %>% dplyr::select(ags, pop_dec_09, applies_census,
                                 one_of(covs), state_id,
                                 inc_party_prior_to_census) %>%
              distinct(ags, .keep_all = T)) %>%
  mutate(runvar = (pop_dec_09 * -1) + 10000) %>%
  filter(applies_census == 1) %>% 
  left_join(time_df) %>% 
  filter(!is.na(elec_late))

##

#### Estimate for all outcomes ####
## Optimal BWs estimated separately

subset_select_late <- !diff_df$state_id == '08' &
  diff_df$elec_late == 1
subset_select_early <- !diff_df$state_id == '08' &
  diff_df$elec_late == 0

## ## ## ## ## ##

out_muni_full <- lapply(olist, function(o) {
  
  out_muni_late <- rdrobust(y = diff_df[subset_select_late, o] %>% pull(!!o), 
                       x = diff_df$runvar[subset_select_late], c = 0,
                       covs = diff_df[subset_select_late, covs])
  out_muni_early <- rdrobust(y = diff_df[subset_select_early, o] %>% pull(!!o), 
                       x = diff_df$runvar[subset_select_early], c = 0,
                       covs = diff_df[subset_select_early, covs])
  
  
  ## Tidy and return
  
  r1 <- out_muni_late %>% tidy_rd(3) %>% 
    mutate(outcome = o, 
           sample = 'Elections less \nproximate to census')
  r2 <- out_muni_early %>% tidy_rd(3) %>% 
    mutate(outcome = o, 
           sample = 'Elections more \nproximate to census')
  
  rbind(r1, r2)
}) %>% 
  reduce(rbind) %>% 
  mutate(election = 'Municipal\nelections')

# Figure A.24: Effect conditional on proximity to census ----

out_muni_full %>% 
  ggplot(aes(sample, estimate)) +
  geom_hline(yintercept = 0, linetype = 'dotted') +
  geom_errorbar(aes(ymin = conf.low, ymax = conf.high),
                width = 0) +
  geom_point(shape = 21, fill = 'white') +
  theme_bw() +
  coord_flip() +
  ylab('RD estimate (percentage points)\n(Outcome: left-wing parties)') +
  xlab('')
